//
//  PKReadMainViewController.m
//  PianKe
//
//  Created by lanou on 15/9/25.
//  Copyright (c) 2015年 李伟伟. All rights reserved.
//

#import "PKReadMainViewController.h"
#import "PKRequestManager.h"
#import "PKReadHeadScrollView.h"
#import "PKReadCollectionViewCell.h"
#import "PKCollectionViewModel.h"
#import "PKHeadScrollViewModel.h"
#import "PKReadDetailViewController.h"
#import "PKHeadWebViewController.h"
@interface PKReadMainViewController ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UIScrollView *mainScrollView;
@property(nonatomic,strong)PKReadHeadScrollView *headScrollView;
@property(nonatomic,strong)NSMutableArray *scrollArray;
@property(nonatomic,strong)NSMutableArray *collectionArray;
@property(nonatomic,strong)UIPageControl *pageControl;
@end

@implementation PKReadMainViewController

-(NSMutableArray *)scrollArray
{
    if (!_scrollArray) {
        _scrollArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _scrollArray;
}

-(NSMutableArray *)collectionArray
{
    if (!_collectionArray) {
        self.collectionArray = [NSMutableArray arrayWithCapacity:0];
        
    }
    return _collectionArray;
}

-(void)loadCollectionView
{
    UICollectionViewFlowLayout *layOut = [[UICollectionViewFlowLayout alloc]init];
    layOut.itemSize = CGSizeMake((SCREEN_WITDTH-12)/3, (SCREEN_WITDTH-12)/3);
    layOut.minimumLineSpacing = 2;
    layOut.minimumInteritemSpacing = 2;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(4, SCREEN_HEIGHT/5 + 8, SCREEN_WITDTH-8, SCREEN_WITDTH-8) collectionViewLayout:layOut];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.scrollEnabled = NO;
    [_mainScrollView addSubview:_collectionView];
    
        [self.collectionView registerClass:[PKReadCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
}

-(void)loadHeadScrollView
{
    _headScrollView = [[PKReadHeadScrollView alloc]initWithFrame:CGRectMake(4, 4, SCREEN_WITDTH-8, SCREEN_HEIGHT/5)];
    _headScrollView.contentSize = CGSizeMake((SCREEN_WITDTH-8)*3, 0);
    _headScrollView.pagingEnabled = YES;
    _headScrollView.delegate = self;
    [_mainScrollView addSubview:_headScrollView];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor purpleColor];
    self.titleLabel.text = @"阅读";
    
    _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 70, SCREEN_WITDTH, SCREEN_HEIGHT-70)];
    _mainScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_mainScrollView];
    
    [self loadHeadScrollView];//加载顶部滚动视图

    
    _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(SCREEN_WITDTH * 3/4, SCREEN_HEIGHT/5-20, 50, 20)];
    _pageControl.numberOfPages = 3;
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    [_mainScrollView addSubview:_pageControl];
    
    
    [self loadCollectionView];//加载集合视图
    
    UIImageView *bottonImageView = [[UIImageView alloc]initWithFrame:CGRectMake(4, 4 + SCREEN_HEIGHT/5 + SCREEN_WITDTH, SCREEN_WITDTH-8, SCREEN_HEIGHT/5)];
    bottonImageView.backgroundColor = [UIColor colorWithRed:0.894 green:0.894 blue:0.773 alpha:1.000];
    _mainScrollView.contentSize = CGSizeMake(0,CGRectGetMaxY(_mainScrollView.frame));
    [_mainScrollView addSubview:bottonImageView];
    
   
    for (int i = 0; i < 3; i++) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goToWebView:)];
        tap.delegate = self;
        [_headScrollView.subviews[i] addGestureRecognizer:tap];
    }
    
    [self requestData];
    
    
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(scrollImage) userInfo:nil repeats:YES];
    
}
static NSInteger i = 0;
-(void)scrollImage
{
    _headScrollView.contentOffset = CGPointMake((SCREEN_WITDTH - 8)* i, 0);
    _pageControl.currentPage = i;
    i++;
    if (i > 2) {
        i = 0;
    }
    
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _headScrollView) {
        _pageControl.currentPage = scrollView.contentOffset.x/(SCREEN_WITDTH-8);
    }
    
}

-(void)goToWebView:(UITapGestureRecognizer *)tap
{
    PKHeadWebViewController *webVC = [[PKHeadWebViewController alloc]init];
    if (tap.view == _headScrollView.subviews[0]) {
        webVC.url = [(PKHeadScrollViewModel *)_scrollArray[0] url];
    }
    else if (tap.view == _headScrollView.subviews[1]) {
        webVC.url = [(PKHeadScrollViewModel *)_scrollArray[1] url];
    }else{
        webVC.url = [(PKHeadScrollViewModel *)_scrollArray[2] url];
    }

   
    [self.navigationController pushViewController:webVC animated:YES];
    
}

-(void)requestData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"63A94D37-33F9-40FF-9EBB-481182338873";
    parDic[@"auth"] = @"BsdsQiiw9K9DCMVzGMTikDJxQ8auML6E82dsXj1lcWP23tBPTxRY4Pw";
    parDic[@"version"] = @"3.0.2";
    [PKRequestManager requestWithType:POST urlString:@"http://api2.pianke.me/read/columns" parDic:parDic finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
     
        NSArray *carouselArray = dic[@"data"][@"carousel"];
        for (NSDictionary *scrollDic in carouselArray) {
            PKHeadScrollViewModel *scrollModel = [[PKHeadScrollViewModel alloc]init];
            [scrollModel setValuesForKeysWithDictionary:scrollDic];
            [self.scrollArray addObject:scrollModel];
        }
         [_headScrollView configureScrollImageView:self.scrollArray];
        
        
        
        NSArray *listArray = dic[@"data"][@"list"];
        for (NSDictionary *collectionDic in listArray) {
            PKCollectionViewModel *collectionModel = [[PKCollectionViewModel alloc]init];
            [collectionModel setValuesForKeysWithDictionary:collectionDic];
            [self.collectionArray addObject:collectionModel];
        }
        
        
        [self.collectionView reloadData];
        
        
        
        
        
    } error:^(NSError *error) {
        NSLog(@"-----------阅读数据请求出错");
    }];
    
    
}




- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _collectionArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PKReadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];

    [cell setConfigureModel:_collectionArray[indexPath.item]];
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PKReadDetailViewController *readDetailVC = [[PKReadDetailViewController alloc]init];
    readDetailVC.titleLabel.text = [_collectionArray[indexPath.item] name];
    PKCollectionViewModel *model = _collectionArray[indexPath.item];//[_collectionArray objectAtIndex:indexPath.item]; 任意对象类型 id 相当于 NSObject,这个类里没有type  向父类里面找 也不会找到 ，所以用 它的一个具有type 属性的子类接收 也即是自己定义的model类；
    readDetailVC.typeid = [model type];
    [self.navigationController pushViewController:readDetailVC animated:YES];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
